// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const TcbRouter = require('tcb-router')

const db = cloud.database()

const wineCollection = db.collection('wine')

const wineParamsCollection = db.collection('wine-params')

const _ = db.command

// 酒
exports.main = async(event, context) => {
  const app = new TcbRouter({
    event
  })


  // 酒添加
  app.router('add', async(ctx, next) => {
    const wine = event.wine
    ctx.body = await wineCollection.add({
      data: {
        ...wine,
        createTime: db.serverDate()
      }
    }).then((res) => {
      console.log('插入成功')
    }).catch((err) => {
      console.error('插入失败')
    })
  })

  // 添加/更新 酒不同规格的价格
  app.router('addParams', async (ctx, next) => {
    const wine = event.wine
    // todo 根据 wrap + isGroup + wineId 更新 price
    const countResult = await wineParamsCollection.where({
      isGroup: wine.isGroup,
      wrap: wine.wrap,
      wineId: wine.wineId
    }).get()
    console.log("查询结果 ", countResult.data[0])

    if (countResult.data.length > 0) {  // 更新
      ctx.body = await wineParamsCollection.doc(countResult.data[0]._id).update({
        data: {
          price: wine.price
        }
      }).then((res) => {
        console.log('更新结果', res)
        res.wineId = wine.wineId
        res.id = countResult.data[0]._id
        res.price = wine.price
        return res
      })
    } else{     // 新增
      ctx.body = await wineParamsCollection.add({
        data: {
          ...wine,
          createTime: db.serverDate()
        }
      }).then((res) => {
        console.log('插入成功')
      }).catch((err) => {
        console.error('插入失败')
      })
    }


    
  })

  // 酒列表
  app.router('list', async(ctx, next) => {

    const keyword = event.keyword

    let w = {}
    if (keyword.trim() != '') {
      w = {
        name: db.RegExp({
          regexp: keyword,
          options: 'i'
        })
      }
    }
    let winebody = await wineCollection.where(w).skip(event.start).limit(event.count)
      .orderBy('createTime', 'asc').get().then((res) => {
        return res.data
      })
    ctx.body = winebody
  })

  // 酒详情
  app.router('detail', async(ctx, next) => {
    let wineId = event.wineId
    // 详情查询
    let detail = await wineCollection
      .doc(wineId)
      .get()
      .then((res) => {
        return res.data
      })
      .catch((err) => {
        console.error('获取酒详情失败')
      })
    
    // 查询参数
    const countResult = await wineParamsCollection.count()
    const total = countResult.total
    let commentList = {
      data: []
    }
    let params = []
    if(total > 0){
      params = await wineParamsCollection
        .where({
          wineId: wineId
        })
        .orderBy('wrap', 'asc')   
        .get()
        .then((res) => {
          return res.data
        })
        .catch((err) => {
          console.error('获取酒参数失败')
        })
    }
     
    ctx.body = {
      detail,
      params
    }
  })


  // 酒编辑
  app.router('edit', async(ctx, next) => {
    let wineId = event.wineId
    let wine = event.wine
    // 详情查询
    let detail = await wineCollection.doc(wineId)
      .update({
        ...wine
      })
      .then((res) => {
        return res.data
      })
      .catch((err) => {
        console.error('编辑失败')
      })
    ctx.body = detail
  })

  // 清空酒
  app.router('del', async(ctx, next) => {

    ctx.body = await wineCollection.where({
        '_id': _.neq('')
      }).remove()
      .then((res) => {
        return res.data
      })
      .catch((err) => {
        console.error('删除失败')
      })
  })

  // 根据参数 id,删除酒参数
  app.router('delWineParam', async (ctx, next) => {
    let id = event.id
    ctx.body = await wineParamsCollection.doc(id).remove()
      .then((res) => {
        return res.data
      })
      .catch((err) => {
        console.error('删除失败')
      })
  })

  return app.serve()
}